{
 "cells": [
  {
   "cell_type": "markdown",
   "source": [
    "Chapter 08\n",
    "# 计算方阵的迹\n",
    "Book_1《编程不难》 | 鸢尾花书：从加减乘除到机器学习"
   ],
   "metadata": {
    "collapsed": false
   }
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "outputs": [],
   "source": [
    "def trace(matrix):\n",
    "    rows = len(matrix)\n",
    "    cols = len(matrix[0])\n",
    "    if rows != cols:\n",
    "        raise ValueError(\"Matrix is not square\")\n",
    "    diagonal_sum = sum(matrix[i][i] for i in range(rows))\n",
    "    return diagonal_sum"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T16:13:58.727968Z",
     "end_time": "2024-07-03T16:13:58.733357Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "outputs": [],
   "source": [
    "# 示例用法\n",
    "A = [[1, 2, 3],\n",
    "     [4, 5, 6],\n",
    "     [7, 8, 9]]"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T16:14:06.612133Z",
     "end_time": "2024-07-03T16:14:06.620659Z"
    }
   }
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "矩阵的迹为: 15\n"
     ]
    }
   ],
   "source": [
    "trace_A = trace(A)\n",
    "print(\"矩阵的迹为:\", trace_A)"
   ],
   "metadata": {
    "collapsed": false,
    "ExecuteTime": {
     "start_time": "2024-07-03T16:14:15.054889Z",
     "end_time": "2024-07-03T16:14:15.065871Z"
    }
   }
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 2
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython2",
   "version": "2.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 0
}
